package com.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author Zhaoluowei
 * @version 1.0
 * @date 2019/8/20 17:53
 */
@Controller
@RequestMapping(value = "/file")
@Slf4j
public class FileController {


    private static final String path = "C:/Users/15010/Desktop/xdDemo/src/main/resources/public/test/";


    @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
    @ResponseBody
    public String fileUpload(@RequestParam("file") MultipartFile file, @RequestParam("username") String username) {
        log.info("username --> " + username);
        log.info("file --> " + file.getOriginalFilename());

        String filename = file.getOriginalFilename();
        log.info("上传的文件名为 --> " + filename);

        //文件后缀
        String suffixName = filename.substring(filename.indexOf("."));
        log.info("文件后缀 --> " + suffixName);

        filename = UUID.randomUUID().toString() + suffixName;
        File destFile = new File(path + filename);

        try {
            file.transferTo(destFile);
            return filename;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "上传失败";
    }


}
